<?php

namespace common\repositories\outstock;

use common\entities\outstock\MyscrmDeliveryOrderEntity;
use common\entities\outstock\MyscrmDeliverySubOrderEntity;
use common\entities\outstock\MyscrmDeliveryProductEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;

/**
 * Created by PhpStorm.
 * User: luoy03
 * Date: 16-12-12
 * Time: 上午11:00
 */
class DeliveryOrderRepository extends BaseRepository
{
    const STATUS_YDH= 10; //已打回
    const STATUS_YSP = 20;//已审批
    const STATUS_YFQ = 25;//发起中，针对特批授权
    const STATUS_YQR = 30;//已确认
    const STATUS_YKT = 40;//已开通
    const STATUS_YSQ = 50;//已授权

    public static $statusMap=[
        self::STATUS_YDH=>'已打回',
        self::STATUS_YFQ=>'发起中',
        self::STATUS_YQR=>'已确认',
        self::STATUS_YKT=>'已开通',
        self::STATUS_YSQ=>'已授权',
    ];
    public static $deliverySceneMap=['正式产品'=>1,'特批'=>4];
    public static $businessPatternMap=['联营'=>2,'直属'=>1];
    public function addDeliveryOrder($data){
        $entity=new MyscrmDeliveryOrderEntity();
        $entity->load($data,'');
        $saveRes=$entity->save();
        if($saveRes===false){
            return self::setAndReturn(__LINE__,$entity->getAllFirstErrorMessage());
        }
        return $saveRes;
    }
    /**
     * @return MyscrmDeliveryOrderEntity|null;
     **/
    public function findDeliveryOrderByDeliveryGuid($deliveryGuid){
        return MyscrmDeliveryOrderEntity::findOne(['delivery_guid' => $deliveryGuid]);
    }
    public function delDeliveryOrderByDeliveryGuid($deliveryGuid,$delSubOrderAndProduct=false){
        if(!$deliveryGuid){
            return false;
        }
        if($delSubOrderAndProduct){
            $transaction=MyscrmDeliveryOrderEntity::getDb()->beginTransaction();
            $delRes=MyscrmDeliveryOrderEntity::deleteAll(['delivery_guid' => $deliveryGuid]);
            if($delRes===false){
                $transaction->rollBack();
                return false;
            }
            $delRes=MyscrmDeliverySubOrderEntity::deleteAll(['delivery_guid' => $deliveryGuid]);
            if($delRes===false){
                $transaction->rollBack();
                return false;
            }
            $delRes=MyscrmDeliveryProductEntity::deleteAll(['delivery_guid' => $deliveryGuid]);
            if($delRes===false){
                $transaction->rollBack();
                return false;
            }
            $transaction->commit();
            return true;
        }else {
            return MyscrmDeliveryOrderEntity::deleteAll(['delivery_guid' => $deliveryGuid]);
        }
    }
}